package com.example.aiinterview.service.impl;

import com.example.aiinterview.model.User;
import com.example.aiinterview.repository.UserRepository;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    // 关键修改：添加 @Lazy 延迟加载，打破循环依赖？
    private final @Lazy PasswordEncoder passwordEncoder;


    @Override
    @Transactional
    public User registerNewUser(String username, String password, String email, String fullName) {
        return registerNewUser(username, password, email, fullName, User.Role.USER);
    }

    @Override
    @Transactional
    public User registerNewUser(String username, String password, String email, String fullName, User.Role role) {
        if (existsByUsername(username)) {
            throw new IllegalArgumentException("Username already exists");
        }

        if (existsByEmail(email)) {
            throw new IllegalArgumentException("Email already exists");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setFullName(fullName);
        user.setRole(role);

        return userRepository.save(user);
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElse(null);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    @Override
    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }

    @Override
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    @Transactional
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    @Override
    @Transactional
    public User updateUser(Long id, String username, String email, String fullName) {
        User user = findById(id).orElseThrow(() -> new IllegalArgumentException("User not found"));
        
        // 检查用户名和邮箱是否被其他用户使用
        if (!username.equals(user.getUsername()) && existsByUsernameAndIdNot(username, id)) {
            throw new IllegalArgumentException("Username already exists");
        }
        
        if (!email.equals(user.getEmail()) && existsByEmailAndIdNot(email, id)) {
            throw new IllegalArgumentException("Email already exists");
        }
        
        user.setUsername(username);
        user.setEmail(email);
        user.setFullName(fullName);
        
        return userRepository.save(user);
    }

    @Override
    @Transactional
    public User updateUserPassword(Long id, String newPassword) {
        User user = findById(id).orElseThrow(() -> new IllegalArgumentException("User not found"));
        user.setPassword(passwordEncoder.encode(newPassword));
        return userRepository.save(user);
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        if (!userRepository.existsById(id)) {
            throw new IllegalArgumentException("User not found");
        }
        userRepository.deleteById(id);
    }

    @Override
    public boolean existsByUsernameAndIdNot(String username, Long id) {
        return userRepository.existsByUsernameAndIdNot(username, id);
    }

    @Override
    public boolean existsByEmailAndIdNot(String email, Long id) {
        return userRepository.existsByEmailAndIdNot(email, id);
    }
}
